<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="85%" @close="closeForm">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="副标题" prop="subTitle">
        <el-input v-model="formData.subTitle" placeholder="请输入副标题" />
      </el-form-item>
      <el-form-item label="主图" prop="mainPic">
        <UploadImg v-model="formData.mainPic" />
      </el-form-item>
      <el-form-item label="文章图册" prop="articlePhotos">
        <UploadImgs v-model="formData.articlePhotos" />
      </el-form-item>
      <el-form-item label="简要" prop="articleShortDesc">
        <el-input v-model="formData.articleShortDesc" type="textarea" placeholder="请输入简要" />
      </el-form-item>
      <el-form-item label="标签" prop="tags">
        <el-select
          v-model="formData.tags"
          multiple
          filterable
          allow-create
          default-first-option
          :reserve-keyword="false"
          placeholder="请选择或输入标签"
        >
          <el-option v-for="item in tagOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="内容" prop="articleContent">
        <MdEditor v-model="formData.articleContent" height="150px" />
      </el-form-item>
      <el-form-item label="文章状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="来源类型" prop="originType">
        <el-radio-group v-model="formData.originType">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.ORIGIN_TYPE)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="来源地址" prop="originUrl">
        <el-input v-model="formData.originUrl" placeholder="请输入来源地址" />
      </el-form-item>
      <el-form-item label="点击量" prop="viewNum">
        <el-input v-model="formData.viewNum" placeholder="请输入点击量" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="formData.sort" placeholder="请输入排序" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm(true)" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="closeForm">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { ArticleDetailApi, ArticleDetailVO } from '@/api/cms/articledetail'
import { ArticleCategoryVO } from '@/api/cms/articlecategory'
import { AppSiteApi } from '@/api/cms/appsite'

/** 文章 表单 */
defineOptions({ name: 'ArticleDetailForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  appSiteId: 0,
  appId: '',
  categoryId: 0,
  title: undefined,
  subTitle: undefined,
  mainPic: undefined,
  articlePhotos: [],
  articleShortDesc: undefined,
  tags: [],
  articleContent: '',
  status: 0,
  originType: 1,
  originUrl: undefined,
  viewNum: 0,
  sort: 0
})
const formRules = reactive({
  appSiteId: [{ required: true, message: '站点编号不能为空', trigger: 'blur' }],
  appId: [{ required: true, message: '站点标识不能为空', trigger: 'blur' }],
  categoryId: [{ required: true, message: '栏目编号不能为空', trigger: 'blur' }],
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '文章状态不能为空', trigger: 'blur' }],
  viewNum: [{ required: true, message: '点击量不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const tagOptions = ref([]) // 标签选项
const interval = ref()
/** 打开弹窗 */
const open = async (type: string, articleCategory: ArticleCategoryVO, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ArticleDetailApi.getArticleDetail(id)
    } finally {
      formLoading.value = false
    }
  } else {
    formData.value.appSiteId = articleCategory.appSiteId
    formData.value.appId = articleCategory.appId
    formData.value.categoryId = articleCategory.id
  }
  await loadTags()
  interval.value = setInterval(() => {
    if (
      formData.value.appSiteId &&
      formData.value.appId &&
      formData.value.categoryId &&
      formData.value.title &&
      formData.value.status !== undefined &&
      formData.value.viewNum !== undefined
    ) {
      submitForm(false)
    }
  }, 5000)
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const loadTags = async () => {
  tagOptions.value = await AppSiteApi.getTagDictionary(
    formData.value.appId,
    formData.value.categoryId
  )
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const closeForm = () => {
  if (interval.value) {
    clearInterval(interval.value)
  }
  dialogVisible.value = false
}
const submitForm = async (close = false) => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  if (close) {
    formLoading.value = true
  }
  try {
    const data = formData.value as unknown as ArticleDetailVO
    if (formType.value === 'create') {
      let id = await ArticleDetailApi.createArticleDetail(data)
      message.success(t('common.createSuccess'))
      if (!close) {
        formData.value.id = id
        formType.value = 'update'
      }
    } else {
      await ArticleDetailApi.updateArticleDetail(data)
      if (close) {
        message.success(t('common.updateSuccess'))
      }
    }
    if (close) {
      dialogVisible.value = false
    }
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
    if (close) {
      if (interval.value) {
        clearInterval(interval.value)
      }
    }
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    appSiteId: 0,
    appId: '',
    categoryId: 0,
    title: undefined,
    subTitle: undefined,
    mainPic: undefined,
    articlePhotos: [],
    articleShortDesc: undefined,
    tags: [],
    articleContent: '',
    status: 1,
    originType: 1,
    originUrl: undefined,
    viewNum: 100,
    sort: 100
  }
  formRef.value?.resetFields()
}
</script>
